#include "stock.h"
#include <iostream>
#include <QFile>
#include <QtCore>

/*
** This is the constructor which takes in 2 inputs of fileString and stockCode to get the data into the class variables.
*/
Stock::Stock(QString fileString, QString stockCode)
{
    qDebug() << "Constructor for Stock Code = " << stockCode;
    QFile file(fileString);
    file.fileName();
    QFileInfo fileInfo(file.fileName());
    qDebug() << "File Path = " << fileInfo.path();

    if (!file.open(QIODevice::ReadWrite)) {
        qDebug() << "File " << fileString << " cannot be opened in generateRandom function!" << endl;
    }
    QString sLowValue = "99999.99"; QString sHighValue = "0";
    QTextStream in(&file);
    QString lineRead;
    bool firstLineRead = true;
    while(!in.atEnd()) {
        lineRead = in.readLine();
        if (lineRead.size() == 0)
            continue;
        QStringList fields = lineRead.split(",");
        if (fields.count() > 1) {
            listRow.insert("stockCode", fields.at(0));
            QString stockPriceString = fields.at(1);

            if (stockPriceString.toFloat() < sLowValue.toFloat()) {
                sLowValue = stockPriceString;
            }
            if (stockPriceString.toFloat() > sHighValue.toFloat()) {
                sHighValue = stockPriceString;
            }
            listRow.insert("price", stockPriceString);

            listRow.insert("time", fields.at(2));
            if (firstLineRead) {
                this->setFirstLineRead(listRow);
                firstLineRead = false;
            }
            fileData << listRow;
        }
    }

    this->setLastLineRead(listRow);

    this->setHighestStockReading(sHighValue);
    this->setLowestStockReading(sLowValue);
    file.close();
}

/*
** This function adds data to the predictor variable which is used by the paintEvent to draw the graph for the predicted values;
*/
void Stock::addPredictorDataToStock(QHash<QString, QString> data)
{
    predictorData << data;
    emit sendSignalToPaintEvent();
}

void Stock::setFirstLineRead(QHash<QString, QString> firstLine) {
    firstLineRead = firstLine;
}

QHash<QString, QString> Stock::getFirstLineRead() {
    return firstLineRead;
}

void Stock::setLastLineRead(QHash<QString, QString> lastLine) {
    lastLineRead = lastLine;
}

QHash<QString, QString> Stock::getLastLineRead() {
    return lastLineRead;
}

QString Stock::getHighestStockReading() {
    return stockHighestValue;
}

void Stock::setHighestStockReading(QString hValue) {
    stockHighestValue = hValue;
    qDebug() << "Setting high value = " << stockHighestValue;
}

QString Stock::getLowestStockReading() {
    return stockLowestValue;
}

void Stock::setLowestStockReading(QString lValue) {
    stockLowestValue = lValue;
    qDebug() << "Setting low value = " << stockLowestValue;
}
